<template>
  <div>
    <el-container direction="vertical" class="vertical">
      <el-main>
        <div>
          <el-form :inline="true" class="tm">
            <el-form-item label="团队">
              <el-select v-model="teamid">
                <el-option v-for="item in getteam" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学员">
              <el-select v-model="userids" collapse-tags multiple>
                <el-option v-for="item in getusers" :key="item.ID" :label="item.name" :value="item.ID"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间">
              <el-date-picker v-model="times" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
                :shortcuts="shortcuts"></el-date-picker>
            </el-form-item>
            <el-row>
              <el-form-item label="题目ID">
                <el-input v-model.number="questionid" placeholder="请输入题单ID"></el-input>
              </el-form-item>
              <el-form-item label="题单ID">
                <el-input v-model.number="questionbankid" placeholder="请输入题单ID"></el-input>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="总条数:">{{ count }} &nbsp;&nbsp;&nbsp;</el-form-item>
                <el-form-item label="用户数:">{{ userids.length }}</el-form-item>
              </el-col>
              <el-col :span="12" class="text-right">
                <el-button type="primary" @click="start">查询</el-button>
                <el-button type="primary" @click="() => download()">下载</el-button>
                <el-button type="primary" @click="() => download(true)">下载全部</el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <el-table :row-class-name="tableRowClassName" :data="userquestion" height="65vh" style="width: 100%">
          <template v-slot:empty>
                <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
              </template>
          <el-table-column prop="user.name" label="用户" width="120"></el-table-column>
          <el-table-column prop="questionid" label="题目ID" width="100"></el-table-column>
          <el-table-column prop="questionbankid" label="题单ID" width="100"></el-table-column>
          <el-table-column prop="createdAt" label="答题时间" :formatter="({ createdAt }) => TimeYH(createdAt)"
            width="150"></el-table-column>
          <el-table-column prop="question.name" label="题目"></el-table-column>
          <el-table-column prop="question.type" label="类型" width="120"></el-table-column>
          <el-table-column prop="dn" label="AC" width="180">
            <template #default="scope">
              <div v-if="scope.row.question.type === '代码'">
                <span v-text="scope.row.tn[1]" :class="scope.row.tn[1]"></span>
              </div>
              <div v-else>{{ scope.row.result }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="测试点" width="350">
            <template #default="scope">
              <div v-if="Array.isArray(scope.row.info)">
                <span v-for="(v, key) in scope.row.data" :key="'a_' + key">
                  [
                  <span v-for="(item, i) in v" :key="scope.$index + '_' + i" :class="item.tn[1]">
                    {{ item.tn[0] }}
                    {{ i !== v.length - 1 ? "," : "" }}
                  </span>
                  ]
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="result" label="其他信息" width="100">
            <template #default="scope">
              <span class="cu" @click="down(scope.row)">下载源码</span>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
      <el-footer class="text-right pt-2 pl-3">
        <el-pagination :page-size="limit" :total="count" @current-change="change" layout="prev, pager, next"
          :current-page="Math.floor(offset / limit) + 1"></el-pagination>
      </el-footer>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import {
  Iobj,
  asyncselectuserquestion,
  asyncselectteamselectuser,
} from "../../../api";
import { ElMessage } from "element-plus";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import {
  computed,
  inject,
  onMounted,
  onUnmounted,
  ref,
  watch,
} from "vue";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { TimeYH } from "../../../util/time";
import { once } from "underscore";
import { utilresult, utilresult1, utilresulttype } from "@/util/jianchatime";
import subtask from "../../../util/subtask";
import { Storekey } from "../../../interface";
import { getExceltodownload } from "../../../util/excel";
import moment from "moment";

interface Iuserquestion1 extends Studycodemodel.Iuserquestion {
  data: Studycodemodel.Iuserquestioninfo[][];
}



const userquestion = ref<Iuserquestion1[]>([]);
const route = useRoute();
const router = useRouter();
const roue = computed(() => {
  return route.query;
});
const count1 = ref(0);
const order = computed(() => {
  return roue.value.order || "ID";
});
const isAdmin = computed(() => {
  if (!user.value) return false;
  const team = getteam.value.find((e) => e.ID === teamid.value);
  if (team?.userid === user.value.ID) return 1;
  const a = team?.teamuser?.find((v) => v.userid === user.value?.ID);
  if (a) {
    return a.isAdmin;
  }
  if (user.value.remarks === "销售助教") return 2;
  return false;
});
const store = useStore(Storekey);
const getteam = computed<Studycodemodel.Iteam[]>(() => {
  return store.getters.getteam;
});
const getusers = ref<Array<Studycodemodel.Iuser | undefined>>([]);
const headnavdialogVisible = inject("headnavdialogVisible", () => { });
const user = computed<Studycodemodel.Iuser | undefined>(() => {
  return store.getters.getuser;
});
const times = ref([Date.now() - 1000 * 60 * 60 * 24 * 7, Date.now()]);
const height = ref(window.innerHeight - 74);
function onresize(e: UIEvent) {
  height.value = window.innerHeight - 74;
}
window.onresize = onresize;

const offset = computed(() => {
  return Number(roue.value.offset) || 0;
});
const isad = computed(() => {
  return Number(roue.value.isad) || 0;
});
const limit = computed(() => {
  return Number(roue.value.limit) || 20;
});
const questionid = ref<number | null>();
const like = ref("");
const teamid = ref<number>();
const userids = ref<Array<number | undefined>>([]);

onUnmounted(() => {
  window.onresize = () => { };
});

onBeforeRouteUpdate(() => {
  questionid.value = Number(roue.value.questionid) || null;

  questionbankid.value =
    (roue.value.questionbankid as unknown as number) || undefined;
});

watch(
  () => route.query,
  () => {
    start();
  }
);

const questionbankid = ref<number>();
function tableRowClassName({ row, rowIndex }: any) {
  if (rowIndex % 2 === 1) {
    return "warning-row";
  } else {
    return "success-row";
  }
}
async function start() {
  if (!user.value) {
    headnavdialogVisible();
    return;
  }
  if (!isAdmin.value) {
    ElMessage.error("权限不足");
    return;
  }
  if (
    !isad.value &&
    [questionid.value, questionbankid.value, teamid.value].filter((e) => e)
      .length === 0
  ) {
    ElMessage.error("请最少添加一种");
    return;
  }

  const userid = userids.value;
  const Iobj: Iobj<Studycodemodel.Iuserquestion> = {
    _limit: limit.value,
    _offset: offset.value,
    _order: 'ID',
    _sortable: 'DESC'
  };
  if (userid.length) {
    Iobj.userid = userid;
  } else {
    ElMessage.error("至少选择一名团员");
    return;
  }
  if (times.value) {
    Iobj.createdAt = {
      lt: times.value[1],
      gt: times.value[0],
    };
  }
  if (questionbankid.value) {
    Iobj.questionbankid = questionbankid.value;
  }
  if (questionid.value) {
    Object.assign(Iobj, {
      questionid: questionid.value,
    });
  }
  const { rows, count } = await asyncselectuserquestion(
    Object.assign(Iobj)
  );
  count1.value = count;
  userquestion.value = rows.map((e) => {
    let { result, info } = e;

    const d = utilresult1(result, info);
    if (Array.isArray(info)) {
      info = info.map((t) => {
        const dd = utilresult(t);
        return {
          ...t,
          tn: dd,
        };
      });
    }
    const f = utilresulttype(e);
    const data = subtask(info);

    return {
      ...f,
      info,
      tn: d,
      data,
    };
  });
}

onMounted(() => {
  questionid.value = Number(roue.value.questionid) || null;
  teamid.value = Number(roue.value.teamid);
  questionbankid.value =
    Number(roue.value.questionbankid as unknown as number) || undefined;

  // start();
});

function change(r: number) {
  router.push({
    name: "答题记录",
    query: {
      limit: limit.value,
      order: order.value,
      offset: (r - 1) * limit.value,
      questionid: questionid.value,
      questionbankid: questionbankid.value,
    },
  });
}

const onc = once(start);

watch(
  () => teamid.value,
  (n) => {
    if (n) {
      const team = getteam.value.find((e) => e.ID === teamid.value);
      asyncselectteamselectuser({
        teamid: n,
      }).then((e) => {
        getusers.value = e.map((v) => {
          const { user, username } = v;
          if (username && user) {
            user.name = username;
          }
          return user;
        });
        if (team && team.user) {
          getusers.value.push(team.user);
        }
        userids.value = getusers.value.map((v) => v?.ID);
        onc();
      });
    } else {
      getusers.value = [];
      userids.value = [];
    }
  }
);

const ALLTYPE = ["Accepted", "Unaccepted", "CompileError", "Unshown"];
function AC(row: Studycodemodel.Iuserquestion) {
  const { result, info } = row;
  if (!result) return ALLTYPE[2];
  if (Array.isArray(info)) {
    const arr = info.filter((v) => {
      if (v.stderr) return true;
      if (v.output && v.output !== v.stdout?.replace(/(\s*$)/g, ""))
        return true;
    });
    return arr.length ? ALLTYPE[1] : ALLTYPE[0];
  }
  return ALLTYPE[1];
}

function AClist(row: Studycodemodel.Iuserquestion) {
  const { result, info } = row;
  if (!result) return [];
  if (Array.isArray(info)) {
    const arr = info.map((v) => {
      if (v.stderr) return "Unaccepted";
      if (v.output && v.output !== v.stdout?.replace(/(\s*$)/g, "")) {
        return "Accepted";
      }
      return "Unaccepted";
    });
    return arr;
  }
  return [];
}


function down(row: Studycodemodel.Iuserquestion) {
  const { context, language } = row;
  if (context) {
    let t = ".cpp";
    if ("c" === language) {
      t = ".c";
    }
    if ("python" === language) {
      t = ".py";
    }
    const bo = new File(
      [context],
      row.user?.name + "_" + row.question?.name + t,
      {
        type: "text/plain",
      }
    );
    var a = document.createElement("a");
    a.download = row.user?.name + "_" + row.question?.name + t;
    a.href = URL.createObjectURL(bo);
    a.click();
  } else {
    ElMessage.error("代码为空");
  }
}
async function download(b?: boolean) {
  const data1: string[][] = [
    ["用户", "题目ID", "题单ID", "答题时间", "题目名称", "AC", "代码"],
  ];
  if (!b) {
    userquestion.value.forEach((e) => {
      let {
        user,
        question,
        questionbankid,
        questionid,
        info,
        context,
        createdAt,
      } = e;
      let { result } = e;
      const d = utilresult1(result, info);
      data1.push([
        String(user?.name),
        String(questionid),
        String(questionbankid),
        TimeYH(createdAt),
        String(question?.name),
        d[0],
        String(context),
      ]);
    });
  } else {
    const userid = userids.value;
    const Iobj: Iobj<Studycodemodel.Iuserquestion> = {
      _limit: count1.value,
      _offset: 0,
      _order: 'ID',
      _sortable: 'DESC'
    };
    if (userid.length) {
      Iobj.userid = userid;
    } else {
      ElMessage.error("至少选择一名团员");
      return;
    }
    if (times.value) {
      Iobj.createdAt = {
        lt: times.value[1],
        gt: times.value[0],
      };
    }
    if (questionbankid.value) {
      Iobj.questionbankid = questionbankid.value;
    }
    if (questionid.value) {
      Object.assign(Iobj, {
        questionid: questionid.value,
      });
    }
    const { rows, count } = await asyncselectuserquestion(
      Object.assign(Iobj)
    );
    rows
      .map((e) => {
        let { result, info } = e;

        const d = utilresult1(result, info);
        if (Array.isArray(info)) {
          info = info.map((t) => {
            const dd = utilresult(t);
            return {
              ...t,
              tn: dd,
            };
          });
        }
        const data = subtask(info);

        return {
          ...e,
          info,
          tn: d,
          data,
        };
      })
      .forEach((e) => {
        let {
          user,
          question,
          questionbankid,
          questionid,
          info,
          context,
          createdAt,
        } = e;
        let { result } = e;
        const d = utilresult1(result, info);
        data1.push([
          String(user?.name),
          String(questionid),
          String(questionbankid),
          TimeYH(createdAt),
          String(question?.name),
          d[0],
          String(context),
        ]);
      });
  }
  if (data1.length > 1) {
    const team = getteam.value.find((e) => e.ID === teamid.value);
    const name = `${team?.name ? team.name : "学生日志"}_${moment(
      times.value[0]
    ).format("YYYYMMDD")}-${moment(times.value[1]).format("YYYYMMDD")}`;
    getExceltodownload(data1, name);
  }
}


const shortcuts = [
  {
    text: "上周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "本周",
    value: () => {
      const end = new Date();

      const start = moment().day(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = moment().date(1).unix() * 1000;
      return [start, end];
    },
  },
  {
    text: "最近90天",
    value: () => {
      const end = new Date();
      const start = moment().date(-90).unix() * 1000;
      return [start, end];
    },
  },
]
</script>

<style scoped>
.gre {
  background-color: var(--color-cheng);
  color: #fff;
}

.gre:hover {
  background-color: var(--color-cheng);
  color: #fff;
}

.gre:active {
  background-color: var(--color-cheng);
  color: #fff;
}

.gre:focus {
  background-color: var(--color-cheng);
  color: #fff;
}

.Accepted {
  color: #53c419;
}

.Unaccepted {
  color: #9d3dcf;
}

.CompileError {
  color: #e74b3c;
}

/* .Unshown {

} */
.vertical {
  height: calc(100vh - 89px);
  background-color: #fff;
}
</style>

<style>
.tm .el-form-item {
  margin-bottom: 12px;
}

.el-table .warning-row {
  --el-table-tr-background-color: #fff;
}

.el-table .success-row {
  --el-table-tr-background-color: #f5f5f5;
}
</style>